package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"house/models"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type HouseController struct {
	beego.Controller
}

func (c *HouseController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	status := c.GetString("status")
	ss := c.GetString("ss")
	img := c.GetString("img")
	house := models.House{
		Name:   name,
		Price:  price,
		Status: status,
		Ss:     ss,
		Img:    img,
	}
	err := models.DB.Model(&models.House{}).Create(&house).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: house,
		}
		c.ServeJSON()
	}
}
func (c *HouseController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}
func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.House{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *HouseController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	var count int64
	var house []models.House
	models.DB.Model(&models.House{}).Count(&count)
	offset := (page - 1) * size
	err := models.DB.Model(&models.House{}).Offset(offset).Limit(size).Find(&house).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData["count"] = count
		pageData["house"] = house
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: house,
		}
		c.ServeJSON()
	}
}
